<?php


namespace app\cms\community;

use app\cms\dto\userInfo;
use app\cms\model\adminUserModel;
use iflow\auth\Authorize\AuthAnnotation;
use iflow\Response;
use iflow\Router\Controller;
use iflow\Router\implement\Request\{ GetMapping, PostMapping };

// 后台用户控制器
#[Controller('cms/api/community/user')]
class adminUser
{
    /**
     * 管理员登录
     * @param userInfo $userInfo
     * @return Response
     */
    #[PostMapping]
    public function adminLogin(userInfo $userInfo): Response
    {
        return (new adminUserModel()) -> login($userInfo);
    }

    /**
     * 获取管理员信息
     * @param int $uid
     * @return Response
     */
    #[GetMapping]
    #[AuthAnnotation('getUserInfo', 'adminUser')]
    public function getAdminUserInfo(int $uid = 0): Response
    {
        $uid = $uid > 0 ? $uid : session('userInfo')['uid'];
        $user = (new adminUserModel()) -> getUser($uid);
        return $user ?
            message() -> success('获取用户信息成功', $user)
            :message() -> unauthorized_error('用户不存在');
    }

    /**
     * 更新后台用户信息
     * @param string $signature
     * @param string $email
     * @param string $password
     * @param string $avatar
     * @param string $nick_name
     * @return Response
     */
    #[PostMapping('update_admin_user_info')]
    #[AuthAnnotation('updateUserInfo', 'adminUser')]
    public function updateUserInfo(
        string $signature = '', string $email = '',
        string $password = '', string $avatar = '',
        string $nick_name = ''
    ): Response {
        $userInfo = [];
        if ($signature !== '') $userInfo['signature'] = $signature;
        if ($password !== '' && mb_strlen($password) > 6) $userInfo['password'] = password_hash($password, PASSWORD_DEFAULT);
        if ($avatar !== '') $userInfo['avatar'] = $avatar;
        if ($email !== '') $userInfo['email'] = $email;
        if ($nick_name !== '') $userInfo['nick_name'] = $nick_name;

        $user = (new adminUserModel()) -> update($userInfo, [
            'uid' => session('userInfo')['uid']
        ]);
        return message() -> success('修改信息成功', $user -> toArray());
    }
}